<template>
  <div class="activity-create page-container">
    <van-nav-bar title="发布活动" left-arrow @click-left="onClickLeft" />

    <div class="form-container content-container">
      <van-form @submit="onSubmit">
        <!-- 活动标题 -->
        <van-cell-group inset>
          <van-field v-model="formData.title" name="title" label="活动标题" placeholder="请输入活动标题" :rules="[{ required: true, message: '请填写活动标题' }]" />
        </van-cell-group>

        <!-- 活动封面 -->
        <van-cell-group inset>
          <van-field name="coverImage" label="活动封面" :rules="[{ required: true, message: '请上传活动封面' }]" :model-value="formData.coverImages.length > 0 ? '已上传' : ''">
            <template #input>
              <van-uploader v-model="formData.coverImages" :max-count="1" :after-read="afterRead" />
            </template>
          </van-field>
        </van-cell-group>

        <!-- 活动类型 -->
        <van-cell-group inset>
          <van-field
            v-model="formData.typeText"
            name="typeText"
            label="活动类型"
            placeholder="请选择活动类型"
            readonly
            clickable
            :rules="[{ required: true, message: '请选择活动类型' }]"
            @click="showTypeActions = true"
          />
        </van-cell-group>

        <van-action-sheet v-model:show="showTypeActions" :actions="activityTypeActions" cancel-text="取消" close-on-click-action @select="onSelectActivityType" />
        <!-- 活动时间 -->
        <van-cell-group inset>
          <van-field
            readonly
            clickable
            name="startTime"
            label="开始时间"
            v-model="formData.startTime"
            placeholder="请选择开始时间"
            @click="showStartTimePicker = true"
            :rules="[{ required: true, message: '请选择开始时间' }]"
          />
        </van-cell-group>

        <van-popup v-model:show="showStartTimePicker" position="bottom" round>
          <div class="datetime-container">
            <div class="datetime-header">
              <div class="cancel" @click="showStartTimePicker = false">取消</div>
              <div class="title">选择开始时间</div>
              <div class="confirm" @click="onManualStartTimeConfirm">确认</div>
            </div>
            <div class="datetime-body">
              <input type="datetime-local" v-model="tempStartTime" class="native-datetime-picker" :min="minDateTimeString" name="start-time-picker" id="start-time-picker" />
            </div>
          </div>
        </van-popup>

        <van-cell-group inset>
          <van-field
            readonly
            clickable
            name="endTime"
            label="结束时间"
            v-model="formData.endTime"
            placeholder="请选择结束时间"
            @click="showEndTimePicker = true"
            :rules="[{ required: true, message: '请选择结束时间' }]"
          />
        </van-cell-group>

        <van-popup v-model:show="showEndTimePicker" position="bottom" round>
          <div class="datetime-container">
            <div class="datetime-header">
              <div class="cancel" @click="showEndTimePicker = false">取消</div>
              <div class="title">选择结束时间</div>
              <div class="confirm" @click="onManualEndTimeConfirm">确认</div>
            </div>
            <div class="datetime-body">
              <input
                type="datetime-local"
                v-model="tempEndTime"
                class="native-datetime-picker"
                :min="formData.startTime ? formatDateForInput(formData.startTime) : minDateTimeString"
                name="end-time-picker"
                id="end-time-picker"
              />
            </div>
          </div>
        </van-popup>

        <!-- 活动地点 -->
        <van-cell-group inset>
          <van-field v-model="formData.startLocation" name="startLocation" label="活动起点" placeholder="请输入活动起点" :rules="[{ required: true, message: '请填写活动起点' }]" />
        </van-cell-group>

        <van-cell-group inset>
          <van-field v-model="formData.endLocation" name="endLocation" label="活动终点" placeholder="请输入活动终点" :rules="[{ required: true, message: '请填写活动终点' }]" />
        </van-cell-group>

        <!-- 活动地点说明 -->
        <van-cell-group inset>
          <van-field v-model="formData.routeDescription" name="routeDescription" label="活动地点说明" type="textarea" rows="3" placeholder="请输入路线说明" />
        </van-cell-group>

        <!-- 参与人数 -->
        <van-cell-group inset>
          <van-field v-model="formData.minParticipants" type="digit" name="minParticipants" label="最小参与人数" placeholder="请输入最小参与人数" :rules="[{ required: true, message: '请填写最小参与人数' }]" />
          <van-field v-model="formData.maxParticipants" type="digit" name="maxParticipants" label="最大参与人数" placeholder="请输入最大参与人数" :rules="[{ required: true, message: '请填写最大参与人数' }]" />
        </van-cell-group>

        <!-- 收费模式 -->
        <van-cell-group inset>
          <van-field
            v-model="formData.feeModeText"
            name="feeModeText"
            label="收费模式"
            placeholder="请选择收费模式"
            readonly
            clickable
            :rules="[{ required: true, message: '请选择收费模式' }]"
            @click="showFeeModeActions = true"
          />
        </van-cell-group>

        <van-action-sheet v-model:show="showFeeModeActions" :actions="feeModeActions" cancel-text="取消" close-on-click-action @select="onSelectFeeMode" />
        <!-- 难度级别 -->
        <van-cell-group inset>
          <van-field
            v-model="formData.difficultyLevelText"
            name="difficultyLevelText"
            label="难度级别"
            placeholder="请选择难度级别"
            readonly
            clickable
            :rules="[{ required: true, message: '请选择难度级别' }]"
            @click="showDifficultyActions = true"
          />
        </van-cell-group>

        <van-action-sheet v-model:show="showDifficultyActions" :actions="difficultyActions" cancel-text="取消" close-on-click-action @select="onSelectDifficulty" />

        <!-- 活动描述 -->
        <van-cell-group inset>
          <van-field v-model="formData.description" name="description" label="活动描述" type="textarea" rows="4" placeholder="请输入活动描述" />
        </van-cell-group>

        <!-- 参与要求 -->
        <van-cell-group inset>
          <van-field v-model="formData.requirements" name="requirements" label="参与要求" type="textarea" rows="3" placeholder="请输入参与要求" />
        </van-cell-group>

        <!-- 装备要求 -->
        <van-cell-group inset>
          <van-field v-model="formData.equipmentRequired" name="equipmentRequired" label="装备要求" type="textarea" rows="3" placeholder="请输入装备要求" />
        </van-cell-group>

        <!-- 标签 -->
        <van-cell-group inset>
          <van-field v-model="formData.tag" name="tag" label="标签" placeholder="请输入活动标签" />
        </van-cell-group>

        <!-- 提交按钮 -->
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit" :loading="submitting">发布活动</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showSuccessToast, showLoadingToast } from 'vant'
import dayjs from 'dayjs'
import { useActivityStore } from '@/stores/activity'
import { activityApi } from '@/api/activity'

const router = useRouter()
const activityStore = useActivityStore()
const submitting = ref(false)
const currentDate = ref(['2022', '06', '01'])
const currentTime = ref(['12', '00'])
const minDate = ref(new Date(2020, 0, 1))
const maxDate = ref(new Date(2025, 5, 1))
// 表单数据
const formData = ref({
  title: '',
  coverImages: [],
  type: '',
  typeText: '',
  startTime: '',
  endTime: '',
  startLocation: '',
  endLocation: '',
  routeDescription: '',
  minParticipants: '1',
  maxParticipants: '10',
  feeMode: '',
  feeModeText: '',
  difficultyLevel: '',
  difficultyLevelText: '',
  description: '',
  requirements: '',
  equipmentRequired: '',
  tag: ''
})

// 活动类型选择
const showTypeActions = ref(false)
const activityTypeActions = [
  // 骑行类活动
  { name: '休闲骑行', value: 'LEISURE_CYCLING' },
  { name: '山地骑行', value: 'MOUNTAIN_CYCLING' },
  { name: '公路骑行', value: 'ROAD_CYCLING' },
  { name: '夜骑', value: 'NIGHT_CYCLING' },
  { name: '亲子骑行', value: 'FAMILY_CYCLING' },
  { name: '环湖骑行', value: 'LAKE_CYCLING' },
  { name: '长途骑行', value: 'LONG_DISTANCE_CYCLING' },

  // 徒步类活动
  { name: '徒步旅行', value: 'HIKING' },
  { name: '城市徒步', value: 'URBAN_HIKING' },
  { name: '山地徒步', value: 'MOUNTAIN_HIKING' },
  { name: '森林徒步', value: 'FOREST_HIKING' },
  { name: '海岸徒步', value: 'COASTAL_HIKING' },
  { name: '峡谷徒步', value: 'CANYON_HIKING' },

  // 露营类活动
  { name: '野外露营', value: 'WILD_CAMPING' },
  { name: '沙滩露营', value: 'BEACH_CAMPING' },
  { name: '森林露营', value: 'FOREST_CAMPING' },
  { name: '湖边露营', value: 'LAKE_CAMPING' },
  { name: '山顶露营', value: 'MOUNTAIN_CAMPING' },

  // 摄影类活动
  { name: '风景摄影', value: 'LANDSCAPE_PHOTOGRAPHY' },
  { name: '人像摄影', value: 'PORTRAIT_PHOTOGRAPHY' },
  { name: '街拍', value: 'STREET_PHOTOGRAPHY' },
  { name: '夜景摄影', value: 'NIGHT_PHOTOGRAPHY' },
  { name: '自然摄影', value: 'NATURE_PHOTOGRAPHY' },

  // 登山类活动
  { name: '登山', value: 'MOUNTAINEERING' },
  { name: '攀岩', value: 'ROCK_CLIMBING' },
  { name: '高山探险', value: 'ALPINE_EXPEDITION' },
  { name: '山脊徒步', value: 'RIDGE_HIKING' },

  // 探索类活动
  { name: '城市探索', value: 'URBAN_EXPLORATION' },
  { name: '古镇探索', value: 'ANCIENT_TOWN_EXPLORATION' },
  { name: '废墟探索', value: 'RUINS_EXPLORATION' },
  { name: '地下探索', value: 'UNDERGROUND_EXPLORATION' },
  { name: '历史建筑探索', value: 'HISTORICAL_BUILDING_EXPLORATION' },

  // 文化类活动
  { name: '文化体验', value: 'CULTURAL_EXPERIENCE' },
  { name: '传统工艺', value: 'TRADITIONAL_CRAFTS' },
  { name: '民俗活动', value: 'FOLK_ACTIVITIES' },
  { name: '文化节', value: 'CULTURAL_FESTIVAL' },
  { name: '历史遗迹', value: 'HISTORICAL_SITES' },

  // 美食类活动
  { name: '美食之旅', value: 'FOOD_TOUR' },
  { name: '街头小吃', value: 'STREET_FOOD' },
  { name: '农家美食', value: 'FARM_FOOD' },
  { name: '特色餐厅', value: 'SPECIALTY_RESTAURANT' },
  { name: '美食节', value: 'FOOD_FESTIVAL' },

  // 志愿类活动
  { name: '环保志愿', value: 'ENVIRONMENTAL_VOLUNTEER' },
  { name: '社区服务', value: 'COMMUNITY_SERVICE' },
  { name: '教育志愿', value: 'EDUCATION_VOLUNTEER' },
  { name: '动物保护', value: 'ANIMAL_PROTECTION' },

  // 水上类活动
  { name: '皮划艇', value: 'KAYAKING' },
  { name: '冲浪', value: 'SURFING' },
  { name: '帆船', value: 'SAILING' },
  { name: '游泳', value: 'SWIMMING' },
  { name: '钓鱼', value: 'FISHING' }
]

const onSelectActivityType = (action) => {
  formData.value.type = action.value
  formData.value.typeText = action.name
  showTypeActions.value = false
  console.log('选择的活动类型:', action.name, action.value)
}

// 时间选择
const showStartTimePicker = ref(false)
const showEndTimePicker = ref(false)

// 监听开始时间选择器的显示状态
watch(showStartTimePicker, (newVal) => {
  if (newVal) {
    // 当打开选择器时，设置初始值为当前时间或已选时间
    tempStartTime.value = formData.value.startTime
      ? formatDateForInput(formData.value.startTime)
      : minDateTimeString.value
  }
})

// 监听结束时间选择器的显示状态
watch(showEndTimePicker, (newVal) => {
  if (newVal) {
    // 当打开选择器时，设置初始值为当前时间、已选时间或开始时间之后
    tempEndTime.value = formData.value.endTime
      ? formatDateForInput(formData.value.endTime)
      : formData.value.startTime
      ? formatDateForInput(
          dayjs(formData.value.startTime)
            .add(1, 'hour')
            .format('YYYY-MM-DD HH:mm')
        )
      : minDateTimeString.value
  }
})

const startDate = computed(() => {
  return formData.value.startTime
    ? new Date(formData.value.startTime)
    : new Date()
})

const onStartTimeConfirm = (value) => {
  formData.value.startTime = dayjs(value).format('YYYY-MM-DD HH:mm')
  showStartTimePicker.value = false
}

const onEndTimeConfirm = (value) => {
  formData.value.endTime = dayjs(value).format('YYYY-MM-DD HH:mm')
  showEndTimePicker.value = false
}

// 收费模式选择
const showFeeModeActions = ref(false)
const feeModeActions = [
  { name: '免费', value: 'FREE' },
  { name: '收费', value: 'PAID' },
  { name: '押金制', value: 'DEPOSIT' }
]

const onSelectFeeMode = (action) => {
  formData.value.feeMode = action.value
  formData.value.feeModeText = action.name
  showFeeModeActions.value = false
  console.log('选择的收费模式:', action.name, action.value)
}

// 难度级别选择
const showDifficultyActions = ref(false)
const difficultyActions = [
  { name: '简单', value: 'EASY' },
  { name: '中等', value: 'MEDIUM' },
  { name: '困难', value: 'HARD' },
  { name: '专业', value: 'EXPERT' }
]

const onSelectDifficulty = (action) => {
  formData.value.difficultyLevel = action.value
  formData.value.difficultyLevelText = action.name
  showDifficultyActions.value = false
  console.log('选择的难度级别:', action.name, action.value)
}

// 图片上传
const afterRead = async (file) => {
  try {
    // 添加上传状态
    file.status = 'uploading'
    file.message = '上传中...'

    console.log('开始上传图片:', file)

    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', file.file)

    console.log('FormData创建成功:', formData)

    // 调用API上传图片
    const response = await activityApi.uploadActivityImage(formData)

    console.log('上传响应:', response)

    // 从响应中获取URL
    const imageUrl = response.data?.url || response.url

    if (!imageUrl) {
      throw new Error('上传成功但未返回图片URL')
    }

    // 上传成功，更新文件状态和URL
    file.status = 'done'
    file.message = '上传成功'
    file.url = imageUrl
    file.content = imageUrl

    console.log('图片上传成功:', imageUrl)
  } catch (error) {
    // 上传失败，更新文件状态
    file.status = 'failed'
    file.message = '上传失败'
    console.error('图片上传失败:', error)
    showToast('图片上传失败，请重试')
  }
}

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 提交表单
const onSubmit = async (values) => {
  try {
    // 检查必填字段
    if (
      !formData.value.coverImages ||
      formData.value.coverImages.length === 0
    ) {
      showToast('请上传活动封面')
      return
    }

    submitting.value = true
    showLoadingToast('提交中...')

    // 数据验证
    if (
      parseInt(formData.value.minParticipants) >
      parseInt(formData.value.maxParticipants)
    ) {
      showToast('最小参与人数不能大于最大参与人数')
      return
    }

    const startTimeDate = new Date(formData.value.startTime)
    const endTimeDate = new Date(formData.value.endTime)
    if (startTimeDate >= endTimeDate) {
      showToast('结束时间必须晚于开始时间')
      return
    }

    // 准备提交的数据
    const activityData = {
      title: formData.value.title,
      description: formData.value.description,
      type: formData.value.type, // 使用type值而不是typeText
      startLocation: formData.value.startLocation,
      endLocation: formData.value.endLocation,
      startTime: new Date(formData.value.startTime).toISOString(),
      endTime: new Date(formData.value.endTime).toISOString(),
      routeDescription: formData.value.routeDescription,
      maxParticipants: parseInt(formData.value.maxParticipants),
      minParticipants: parseInt(formData.value.minParticipants),
      difficultyLevel: formData.value.difficultyLevel,
      requirements: formData.value.requirements,
      equipmentRequired: formData.value.equipmentRequired,
      feeMode: formData.value.feeMode,
      feeDescription: '', // 添加空的费用说明
      tag: formData.value.tag || undefined
    }

    // 获取已上传的图片URL
    const coverImage = formData.value.coverImages[0]
    if (coverImage && (coverImage.url || coverImage.content)) {
      activityData.cover = coverImage.url || coverImage.content
    } else {
      showToast('请上传活动封面')
      submitting.value = false
      return
    }

    console.log('提交活动数据:', activityData)

    // 调用API创建活动
    const result = await activityApi.createActivity(activityData)

    showSuccessToast('发布成功')

    // 创建成功后跳转到活动详情页
    router.push(`/activity/detail/${result.id}`)
  } catch (error) {
    console.error('提交失败:', error)
    showToast('发布失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 在script部分添加以下内容
const tempStartTime = ref('')
const tempEndTime = ref('')

// 获取当前时间的ISO字符串格式，用于datetime-local输入框
const minDateTimeString = computed(() => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day}T${hours}:${minutes}`
})

// 手动确认开始时间
const onManualStartTimeConfirm = () => {
  if (tempStartTime.value) {
    formData.value.startTime = dayjs(tempStartTime.value).format(
      'YYYY-MM-DD HH:mm'
    )
    showStartTimePicker.value = false
    console.log('设置开始时间:', formData.value.startTime)
  }
}

// 手动确认结束时间
const onManualEndTimeConfirm = () => {
  if (tempEndTime.value) {
    console.log(
      '验证时间 - 开始:',
      formData.value.startTime,
      '结束:',
      tempEndTime.value
    )

    // 直接比较时间戳
    if (formData.value.startTime) {
      const startTimestamp = new Date(formData.value.startTime).getTime()
      const endTimestamp = new Date(tempEndTime.value).getTime()

      console.log('时间戳比较:', startTimestamp, endTimestamp)

      if (endTimestamp <= startTimestamp) {
        showToast('结束时间必须大于开始时间')
        return
      }
    }

    formData.value.endTime = dayjs(tempEndTime.value).format('YYYY-MM-DD HH:mm')
    showEndTimePicker.value = false
    console.log('设置结束时间:', formData.value.endTime)
  }
}

// 格式化日期为input[type=datetime-local]所需的格式
const formatDateForInput = (dateString) => {
  if (!dateString) return minDateTimeString.value

  try {
    const date = dayjs(dateString)
    return date.format('YYYY-MM-DDTHH:mm')
  } catch (error) {
    console.error('Date formatting error:', error)
    return minDateTimeString.value
  }
}
</script>

<style scoped>
.activity-create {
  padding-bottom: 20px;
}

.form-container {
  padding: 16px 0;
}

:deep(.van-cell-group--inset) {
  margin: 12px 16px;
}

:deep(.van-uploader) {
  padding-top: 8px;
}

:deep(.van-uploader__upload) {
  width: 80px;
  height: 80px;
}

:deep(.van-uploader__preview-image) {
  width: 80px;
  height: 80px;
}

:deep(.van-action-sheet__content) {
  max-height: 50vh;
  overflow-y: auto;
}

:deep(.van-datetime-picker) {
  height: auto;
}

/* 添加以下样式 */
.datetime-container {
  background-color: #fff;
  border-radius: 16px 16px 0 0;
  max-height: 40vh; /* 限制最大高度为视口高度的40% */
  overflow-y: auto; /* 如果内容超出，允许滚动 */
}

.datetime-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 44px;
  padding: 0 16px;
  border-bottom: 1px solid #ebedf0;
  position: sticky; /* 使标题栏固定在顶部 */
  top: 0;
  background-color: #fff;
  z-index: 1;
}

.datetime-header .title {
  font-size: 16px;
  font-weight: 500;
}

.datetime-header .cancel {
  color: #969799;
  font-size: 14px;
}

.datetime-header .confirm {
  color: #1989fa;
  font-size: 14px;
}

.datetime-body {
  padding: 20px;
  display: flex;
  justify-content: center;
}

.native-datetime-picker {
  width: 100%;
  height: 36px;
  font-size: 16px;
  border: 1px solid #ebedf0;
  border-radius: 4px;
  padding: 0 12px;
}

.activity-type-list {
  max-height: 50vh;
  overflow-y: auto;
  padding: 16px;
}

.activity-type-item {
  padding: 12px 0;
  text-align: center;
  font-size: 16px;
  border-bottom: 1px solid #ebedf0;
}

.activity-type-item:last-child {
  border-bottom: none;
}
</style>





